package com.meixiaoliang.portal.core.api;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 参考 https://my.oschina.net/bianxin/blog/2876640
 */
public class ApiForwardInterceptor extends HandlerInterceptorAdapter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // api 请求地址, 进行转发操作。转发可以携带请求参数且后台行为, 外部地址不变即外部无法感知该行为
        if (request.getRequestURI().startsWith("/api/")) {
            try {
                logger.debug("api forward: {}", request.getRequestURI().substring(4));
                request.getRequestDispatcher(request.getRequestURI().substring(4)).forward(request, response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
            //
            return false;
        }

        return true;

    }

}
